/**
 * Created by xcold on 2016/1/29
 */

var ParkModel = require('../dao/park')();
var errorIndex = {
    status: 40001,
    msg: '页码格式错误或超出范围'
};
var errorCount = {
    status: 40002,
    msg: '找不到停车场记录'
};
var errorQuery = {
    status: 40004,
    msg: '无结果'
};

exports.cors = function(req, res, next) {
    res.header('Access-Control-Allow-Origin', '*');
    res.header('Access-Control-Allow-Headers', 'Content-Type, Content-Length, Authorization, Accept, X-Requested-With , yourHeaderFeild');
    res.header('Access-Control-Allow-Methods', 'PUT, POST, GET, DELETE, OPTIONS');
}

var checkPageIndex = function(index) {
    return index !== undefined && parseInt(index) && index > 0 && index < 10000;
}

exports.getParkList = function(req, res, next) {
    // res.header('Access-Control-Allow-Origin', '*');
    // res.header('Access-Control-Allow-Headers', 'Content-Type, Content-Length, Authorization, Accept, X-Requested-With , yourHeaderFeild');
    // res.header('Access-Control-Allow-Methods', 'PUT, POST, GET, DELETE, OPTIONS');
    var index = req.query.pageIndex;
    if (!checkPageIndex(index)) {
        res.json(errorIndex);
        return false;
    }
    ParkModel.getParkList(index, function(err, doc) {
        if (doc.length < 1) {
            res.json(errorIndex);
            return false;
        }
        var data = {
            status: 40000,
            msg: '成功获取停车场列表',
            parkList: doc
        };
        res.json(data);
    })
};

exports.getParkCount = function(req, res, next) {
    ParkModel.getTotalCount(function(err, count) {
        var data = {
            status: 40000,
            msg: '成功获取停车场数量',
            count: count
        }
        res.json(data);
    });
};

exports.getParkListByKey = function(req, res, next) {
    var query = req.query.keyword;
    var index = req.query.pageIndex;
    if (!checkPageIndex(index)) {
        res.json(errorIndex);
        return false;
    }
    ParkModel.getParkListByKey(index, query, function(err, doc) {
        if (doc.length < 1) {
            res.json(errorQuery);
            return false;
        }
        var data = {
            status: 40000,
            msg: '成功获取停车场列表',
            parkList: doc
        };
        res.json(data);
    })
};